<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FieldSchema } from '../types/masterDetail'
import { ElMessage, ElMessageBox } from 'element-plus'

interface Props {
  title: string
  headerFields: FieldSchema[]
  detailColumns: FieldSchema[]
}

const props = defineProps<Props>()

type Row = Record<string, any>

const headerData = reactive<Record<string, any>>({})
props.headerFields.forEach(f => {
  headerData[f.key] = null
})

const rules = reactive<Record<string, any[]>>({})
props.headerFields.forEach(f => {
  if (f.required) {
    rules[f.key] = [{ required: true, message: `请填写${f.label}`, trigger: 'blur' }]
  }
})

const rows = ref<Row[]>([])
let autoId = 1
const selectedIndex = ref<number | null>(null)

const savedItems = ref<Array<{ header: Record<string, unknown>; rows: Row[] }>>([])

function addRow() {
  const row: Row = {}
  props.detailColumns.forEach(c => {
    row[c.key] = null
  })
  // 行唯一ID，便于后续按ID定位与更新
  ;(row as any)._id = autoId++
  rows.value.push(row)
}

function removeSelectedRow() {
  if (selectedIndex.value === null) return
  rows.value.splice(selectedIndex.value, 1)
  selectedIndex.value = rows.value.length ? Math.min(selectedIndex.value, rows.value.length - 1) : null
}

function clearAll() {
  props.headerFields.forEach(f => {
    headerData[f.key] = null
  })
  rows.value = []
  selectedIndex.value = null
}

function save() {
  // 简单校验：必填字段
  const missingHeader = props.headerFields.filter(f => f.required && (headerData[f.key] === null || headerData[f.key] === ''))
  if (missingHeader.length) {
    ElMessage.warning(`请填写表头必填项：${missingHeader.map(m => m.label).join('、')}`)
    return
  }
  const hasEmptyRequiredInRows = rows.value.some(r => props.detailColumns.some(c => c.required && (r[c.key] === null || r[c.key] === '')))
  if (hasEmptyRequiredInRows) {
    ElMessage.warning('请完善表体必填项')
    return
  }
  ElMessageBox.confirm('确认保存当前数据吗？', '确认', { type: 'warning' })
    .then(() => {
  // 保存：若存在相同 header 的记录则更新，否则新增
  const snapshotRows = JSON.parse(JSON.stringify(rows.value)) as Row[]
  const existsIndex = savedItems.value.findIndex(s => JSON.stringify(s.header) === JSON.stringify(headerData))
  if (existsIndex >= 0) {
    savedItems.value[existsIndex].rows = snapshotRows
  } else {
    savedItems.value.push({ header: { ...headerData }, rows: snapshotRows })
  }
  ElMessage.success('保存成功，已进入编辑模式')
      ElMessage.success('保存成功')
    })
    .catch(() => {})
}

function onSelectRow(index: number) {
  selectedIndex.value = index
}

function getSavedHeaderValue(item: { header: Record<string, unknown> }, key: string) {
  const header = item.header as Record<string, unknown>
  const value = header[key]
  return value == null ? '' : String(value)
}

function getRowValue(r: Row, key: string) {
  const value = r[key]
  return value == null ? '' : value
}

function scrollToRowById(rowId: number) {
  const idx = rows.value.findIndex(r => (r as any)._id === rowId)
  if (idx >= 0) {
    selectedIndex.value = idx
    // 轻微提示
    ElMessage.info(`已定位到行 #${idx + 1}`)
  } else {
    ElMessage.warning('未找到对应行')
  }
}
</script>

<template>
  <div class="md-wrap">
    <el-affix :offset="0">
      <div class="md-toolbar">
        <h2 class="md-title">{{ props.title }}</h2>
        <div class="md-actions">
          <el-button @click="clearAll">新增</el-button>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="clearAll">撤销</el-button>
          <el-popconfirm title="确认删除并清空当前编辑内容？" confirm-button-text="确定" cancel-button-text="取消" @confirm="clearAll">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </div>
      </div>
    </el-affix>

    <el-form :model="headerData" :rules="rules" label-width="100px" class="md-form">
      <el-row :gutter="12">
        <el-col v-for="f in props.headerFields" :key="f.key" :xs="24" :sm="12" :md="8" :lg="6">
          <el-form-item :label="f.label" :prop="f.key" :required="f.required">
            <template v-if="f.type === 'select' && f.options">
              <el-select v-model="headerData[f.key]" placeholder="请选择">
                <el-option v-for="opt in f.options" :key="String(opt.value)" :label="opt.label" :value="opt.value" />
              </el-select>
            </template>
            <template v-else-if="f.type === 'date'">
              <el-date-picker v-model="headerData[f.key]" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
            </template>
            <template v-else>
              <el-input v-model="headerData[f.key]" :placeholder="f.placeholder || ''" />
            </template>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="md-body">
      <div class="md-body-actions">
        <el-button @click="addRow">增行</el-button>
        <el-button type="danger" @click="removeSelectedRow" :disabled="selectedIndex === null">删行</el-button>
        <el-input-number v-model="autoId" :min="1" :controls="false" size="small" style="width:120px" />
        <el-button size="small" @click="scrollToRowById(autoId)">按ID定位</el-button>
      </div>

      <el-table :data="rows" highlight-current-row size="small" border stripe @current-change="(_, row) => { selectedIndex = rows.indexOf(row) }" style="width: 100%">
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column v-for="col in props.detailColumns" :key="col.key" :label="col.label">
          <template #default="{ row }">
            <template v-if="col.type === 'select' && col.options">
              <el-select v-model="row[col.key]" placeholder="请选择">
                <el-option v-for="opt in col.options" :key="String(opt.value)" :label="opt.label" :value="opt.value" />
              </el-select>
            </template>
            <template v-else-if="col.type === 'date'">
              <el-date-picker v-model="row[col.key]" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
            </template>
            <template v-else>
              <el-input v-model="row[col.key]" />
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!rows.length" class="empty">点击“增行”添加数据</div>
    </div>

    <section class="md-saved">
      <h3>已保存记录</h3>
      <div v-if="!savedItems.length" class="empty">暂无</div>
      <el-card v-for="(item, i) in savedItems" :key="i" class="saved-item" shadow="never">
        <div class="saved-header">
          <span v-for="f in props.headerFields" :key="f.key" class="kv">
            <b>{{ f.label }}:</b>
            <i>{{ getSavedHeaderValue(item, f.key) }}</i>
          </span>
        </div>
        <el-table :data="item.rows" size="small" border>
          <el-table-column label="序号" width="70" type="index" />
          <el-table-column v-for="col in props.detailColumns" :key="col.key" :prop="col.key" :label="col.label" />
        </el-table>
      </el-card>
    </section>
  </div>

</template>

<style scoped>
.md-wrap { padding: 16px; }
.md-title { margin: 0; font-size: 18px; }
.md-toolbar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
.md-actions { display: flex; gap: 8px; }
.btn { padding: 6px 12px; }
.req { color: #ef4444; margin-left: 2px; }
.md-form { background: #fff; padding: 8px 12px; border-radius: 6px; border: 1px solid #eee; }
.md-body { margin-top: 16px; }
.md-body-actions { margin-bottom: 8px; display: flex; gap: 8px; }
.table .empty { text-align: center; color: #888; }
.md-saved { margin-top: 20px; }
.saved-item { margin-bottom: 12px; }
.saved-header { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 8px; }
.saved-header .kv b { margin-right: 4px; }
@media (max-width: 900px) {}
</style>


<script lang="ts">
export default {}
</script>

